/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.fjs.liyq.service.impl;

import edu.fjs.liyq.dao.ProductDao;
import edu.fjs.liyq.dao.impl.ProductDaoImpl;
import edu.fjs.liyq.entity.Product;
import edu.fjs.liyq.exception.InsufficientStockException;
import edu.fjs.liyq.service.ProductService;
import java.util.List;

/**
 *
 * @author danny
 */
public class ProductServiceImpl implements ProductService {
    
    ProductDao dao = new ProductDaoImpl();

    @Override
    public List<Product> getProductListWithPage(int pageNum, int rowCount) {
        return dao.selectPage(pageNum, rowCount);
    }

    @Override
    public int getProductCount() {
        return dao.selectCount();
    }

    @Override
    public boolean addProduct(Product product) {
        return dao.insert(product) == 1 ? true : false;
    }

    @Override
    public Product getById(long prodId) {
        return dao.select(prodId);
    }

    @Override
    public int checkStock(long productId, int num) {
        Product select = dao.select(productId);
        if (select == null) {
            throw new InsufficientStockException();
//            return Integer.MIN_VALUE;
        } else if (select.getEpStock() - num >= 0) {
            return select.getEpStock() - num;
        } else {
            throw new InsufficientStockException();
        }
    }

    @Override
    public boolean decreaseStock(long productId, int num) {
        boolean result = false;
        Product select = dao.select(productId);
        if (select != null) {
            if (select.getEpStock() - num > 0) {
                select.setEpStock(select.getEpStock() - num);
                dao.update(select);
                result = true;
            }
        }
        return result;
    }
    
}
